package givenchy

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
@Secured(['ROLE_ADMIN'])
class InviteController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [inviteInstanceList: Invite.list(params), inviteInstanceTotal: Invite.count()]
    }

    // 生成随机邀请码
    def random(){
        def array = ["0","1","2","3","4","5","6","7","8","9",
                            "a","b","c","d","e","f","g","h","i","j","k","l","m","n","u",
                            "t","s","o","x","v","p","q","r","w","y","z","A","B","C",
                            "D","E","F","G","H","I","J","K","L","M","N","U",
                            "T","S","O","X","V","P","Q","R","W","Y","Z"];
        StringBuffer str
        def flag = true  //不重复
        while(flag){
            str = new StringBuffer();
            for(int i = 0;i < 6; i++){
                Double number=Math.random()*(array.size()-1);
                str.append(array[number.intValue()]);
            }
            if(Invite.countByCode(str) == 0){
                flag = false
            }
        }
        return str.toString()
    }
    // 从这里生成
    def create = {
        def inviteInstance = new Invite()
        def randomNum = random()
        inviteInstance.code = randomNum
        if (inviteInstance.save(flush: true)) {
            flash.message = "成功生成邀请码！"
        }
        else {
            inviteInstance.code = ''
            flash.message = "邀请码生成失败！！"
        }
        //inviteInstance.properties = params
        return [inviteInstance: inviteInstance]
    }
 
    def delete = {
        def inviteInstance = Invite.get(params.id)
        if (inviteInstance) {
            try {
                inviteInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'invite.label', default: 'Invite'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'invite.label', default: 'Invite'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'invite.label', default: 'Invite'), params.id])}"
            redirect(action: "list")
        }
    }
}
